module.exports = app => {
    const express = require('express')
    const router = express.Router({
        mergeParams: true
    })

    const path = require('path')
    const jwt = require('jsonwebtoken')
    const ad = require('../../model/AdminUser')
    const assert = require('http-assert')
    const auth = async(req, res, next) => {
        assert(req.headers.authorization, 401, '请先登录')
        const token = String(req.headers.authorization || null).split(' ').pop()
        assert(token, 401, '请提供token')
        const { _id } = jwt.verify(token, app.get('secret'))
        assert(_id, 422, '请提供正确的token')
        const user = ad.findById(_id)
        assert(user, 422, '请提供正确的token')
        await next()
    }
    const verifyToken = async(req, res, next) => {
        const token = req.headers.token
        if (!token) res.status(422).send('请先登录并提供token')
        const { _id } = jwt.verify(token, app.get('secret'))
        if (!_id) res.status(500).send('请提供正确的token ')
            /* console.log('token------------id');
            console.log(_id); */
            // return id
        await next()
    }

    // 创建接口
    router.post('/', auth, async(req, res) => {

        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 删除接口
    router.delete('/:id', auth, async(req, res) => {
        const model = await req.Model.findByIdAndDelete(req.params.id, req.body)
        res.send(model)
    })

    // 修改接口
    router.put('/:id', auth, async(req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })


    // 查询接口
    router.get('/', auth, async(req, res) => {

        const items = await req.Model.find().sort({ 'jf': -1 }).populate('parent').populate('sport').populate({
                path: 'student',
                populate: {
                    path: 'parent'
                }
            })
            // const items = await req.Model.find().setOptions(queryOptions)
        res.send(items)
    })

    // 查询详情接口
    router.get('/:id', auth, async(req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })

    app.use('/admin/api/rest/:resource', auth, async(req, res, next) => {
        const modelName = require('inflection').classify(req.params.resource)
        req.Model = require(`../../model/${modelName}`)
        next()
    }, router)

    app.post('/admin/api/sportManage/search', auth, async(req, res) => {
        const Model = require('../../model/Apply')
        const rs = await Model.find(req.body).sort({ 'score': 1 }).populate('parent').populate('sport').populate({
            path: 'student',
            populate: {
                path: 'parent'
            }
        })
        console.log('-------------rs');
        console.log(rs);
        // console.log(req.body);
        res.send(rs)

    })


    app.post('/admin/api/login', async(req, res) => {


        const { userName, pwd } = req.body
        const user = await ad.findOne({
                username: userName
            })
            // 先判断用户是否存在
        assert(user, 422, '用户不存在')
            // if(!user) return res.status(422).send('用户不存在')

        /* // 使用bcrypt对比密码是否正确
        const valida = require('bcrypt').compareSync(
            password, user.pwd
        ) */
        if (user.password !== pwd) res.status(422).send('密码错误')
            // assert(valida, 422, '密码错误')

        // if(!valida) return res.status(422).send('')

        // 返回token

        const token = jwt.sign({
            _id: user._id
        }, app.get('secret'))
        res.send({
            userName,
            token
        })


    })

    // 上传图片处理
    const multer = require('multer')
    const upload = multer({ dest: path.join(__dirname, '../../uploads') })
    app.post('/admin/api/upload', upload.single('file'), async(req, res) => {

        const file = req.file
        file.url = `http://localhost:3000/uploads/${file.filename}`
        res.send(file)
    })



    //错误处理函数
    app.use(async(err, req, res, next) => {
        res.status(err.statusCode || 500).send(err.message)
    })




    //临时测试
    /*    app.post('/api/login', async(req, res) => {
   
           const tokens = {
               admin: {
                   token: 'admin-token'
               },
               editor: {
                   token: 'editor-token'
               }
           }
           const token = tokens['admin']
               // const token = tokens['admin']
           res.send(token)
       }) */
    app.post('/api/login', async(req, res) => {
        const { username, password } = req.body
        const user = await require('../../model/AdminUser').findOne({
                username: username
            })
            // const user = await require('../../model/AdminUser').find()

        if (!user) {
            res.status(422).send('用户不存在')
        }

        if (user.password !== password) {
            res.status(500).send('密码错误')
        }
        const token = jwt.sign({
            _id: user._id
        }, app.get('secret'))
        res.send({
            user,
            token
        })

    })

    app.post('/api/logout', async(req, res) => {


        // const token = tokens['admin']
        res.send('success')
    })

    app.post('/api/userInfo', verifyToken, async(req, res) => {
        // console.log('req.header----------');
        // console.log(req.headers);
        const { token } = req.headers
        const { _id } = jwt.verify(token, app.get('secret'))
        assert(_id, 422, '请提供正确的token')
        const user = await require('../../model/AdminUser').findById(_id)
            // const token = tokens['admin']
        res.send(user)
    })

    app.get('/api/users', verifyToken, async(req, res) => {
        const model = require('../../model/AdminUser')
        const rs = await model.find()
        res.send(rs)
    })
    app.post('/api/users/search', verifyToken, async(req, res) => {
        const { pageSize, currentPage } = req.body
        delete req.body.pageSize
        delete req.body.currentPage
        const total = await require('../../model/AdminUser').find(req.body).count()

        const model = await require('../../model/AdminUser').find(req.body).skip((currentPage - 1) * pageSize).limit(pageSize)
            // const model = require('../../model/AdminUser').find(req.body)
            // const rs = await model.find()
        res.send({
            model,
            total
        })
    })

    app.post('/api/users/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/AdminUser').findById(req.params.id)
        res.send(model)
    })
    app.put('/api/users/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/AdminUser').findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 创建接口
    app.post('/api/users', verifyToken, async(req, res) => {
        const { username } = req.body
        const rs = await require('../../model/AdminUser').find({
            username: username
        })
        if (rs.length >= 1) res.status(422).send('用户名已存在，请登录或者更换用户名')
        else {
            const model = await require('../../model/AdminUser').create(req.body)
            res.send(model)
        }
    })

    // 删除接口
    app.post('/api/users/delete/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/AdminUser').findByIdAndDelete(req.params.id, req.body)
        res.send(model)
    })

    //添加班级
    app.post('/api/addClass', verifyToken, async(req, res) => {

            const rs = await require('../../model/Class').find({
                classNum: req.body.classNum
            })
            if (rs.length >= 1) return res.status(422).send('班级编号重复')
            const model = await require('../../model/Class').create(req.body)
            res.send(model)
        })
        //查询班级
    app.get('/api/getClass', verifyToken, async(req, res) => {
        const model = await require('../../model/Class').find()
        res.send(model)
    })
    app.post('/api/getClass', verifyToken, async(req, res) => {
        const model = await require('../../model/Class').find(req.body)
        res.send(model)
    })
    app.post('/class/getId/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/Class').findById(id)
        res.send(model)
    })



    app.post('/api/deleteClass/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/Class').findByIdAndDelete(req.params.id, req.body)
        res.send(model)
    })
    app.put('/api/class/edit/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/Class').findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    /* 添加学生 */
    app.post('/api/addStudent', verifyToken, async(req, res) => {
        const { stuNum } = req.body
        const rs = await require('../../model/Student').find({
            stuNum: stuNum
        })
        console.log('stu---------');
        console.log(rs);
        if (rs.length >= 1) return res.status(422).send('学号重复')
        const model = await require('../../model/Student').create(req.body)
        res.send(model)
    })

    app.get('/api/getStudent', verifyToken, async(req, res) => {
        const model = await require('../../model/Student').find().populate('class')
        res.send(model)
    })
    app.post('/api/student/search', verifyToken, async(req, res) => {
        const model = await require('../../model/Student').find(req.body).populate('class')
        res.send(model)
    })
    app.post('/api/getStudent', verifyToken, async(req, res) => {
        const model = await require('../../model/Student').find(req.body).populate('class')
        res.send(model)
    })
    app.post('/api/deleteStudent/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/Student').findByIdAndDelete(req.params.id, req.body)
        res.send(model)
    })
    app.put('/api/student/edit/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/Student').findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    //添加比赛项目
    app.post('/api/sportItem/add', verifyToken, async(req, res) => {
        const rs = await require('../../model/SportItem').find({
            name: req.body.name
        })
        if (rs.length >= 1) return res.status(422).send('比赛名称重复')
        const model = await require('../../model/SportItem').create(req.body)
        res.send(model)
    })
    app.get('/api/sportItem/info', verifyToken, async(req, res) => {
        const model = await require('../../model/SportItem').find()
        res.send(model)
    })
    app.post('/api/sportItem/info', verifyToken, async(req, res) => {
        const model = await require('../../model/SportItem').find(req.body)
        res.send(model)
    })
    app.put('/api/sportItem/edit/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/SportItem').findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })
    app.post('/api/sportItem/delete/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/SportItem').findByIdAndDelete(req.params.id, req.body)
        res.send(model)
    })

    //报名
    app.post('/api/apply/sportItem', verifyToken, async(req, res) => {
        const model = await require('../../model/SportItem').find(req.body)
        res.send(model)
    })
    app.post('/api/apply/search', verifyToken, async(req, res) => {
        const model = await require('../../model/Apply').find(req.body).populate('student').populate('sport')
        res.send(model)
    })
    app.get('/api/apply/allInfo', verifyToken, async(req, res) => {
        const sportItem = await require('../../model/SportItem').find()
        const student = await require('../../model/Student').find()
        res.send({
            sportItem,
            student
        })
    })
    app.post('/api/apply/student', verifyToken, async(req, res) => {
        const model = await require('../../model/Student').find(req.body)
        res.send(model)
    })
    app.post('/api/apply/add', verifyToken, async(req, res) => {
        const { peopleLimit, sport, student } = req.body
        if (peopleLimit == "单人") {
            const result = await require('../../model/Apply').find({
                student: student,
                sport: sport,
            })
            if (result.length == 1) return res.status(422).send('不能重复报名同一项目')
            const array = await require('../../model/Apply').find({
                peopleLimit: "单人"
            })

            var repeat = 0;
            for (let i = 0; i < array.length; i++) {
                if (req.body.student == array[i].student) {
                    repeat++;
                }
                if (repeat > 2) {
                    return res.status(422).send('每人限报三项单人项目')

                }
            }
            const model = await require('../../model/Apply').create(req.body)
            res.send(model)
        } else {
            const model = await require('../../model/Apply').create(req.body)
            res.send(model)
        }

    })
    app.post('/api/apply/list', verifyToken, verifyToken, async(req, res) => {
        const { pageSize, currentPage } = req.body
        delete req.body.pageSize
        delete req.body.currentPage
        if (req.body.order == 1) {
            delete req.body.order
            const total = await require('../../model/Apply').find(req.body).count()

            const model = await require('../../model/Apply').find(req.body).sort({ "score": 1 }).skip((currentPage - 1) * pageSize).limit(pageSize).populate('student').populate('sport').populate({
                path: 'student',
                populate: {
                    path: 'class'
                }
            })
            return res.send({
                model,
                total
            })
        } else {
            delete req.body.order
            const total = await require('../../model/Apply').find(req.body).count()
            const model = await require('../../model/Apply').find(req.body).sort({ "daoci": 1 }).skip((currentPage - 1) * pageSize).limit(pageSize).populate('student').populate('sport').populate({
                path: 'student',
                populate: {
                    path: 'class'
                }
            })
            return res.send({
                model,
                total
            })
        }


    })
    app.post('/api/apply/list/jf', verifyToken, async(req, res) => {
            const { pageSize, currentPage } = req.body
            delete req.body.pageSize
            delete req.body.currentPage
            const total = await require('../../model/Apply').find(req.body).count()
            const model = await require('../../model/Apply').find(req.body).sort({ "score": 1 }).skip((currentPage - 1) * pageSize).limit(pageSize).populate('student').populate('sport').populate({
                path: 'student',
                populate: {
                    path: 'class'
                }
            })

            res.send({
                model,
                total
            })
        })
        //比赛管理
    app.get('/api/applyManage/list', verifyToken, verifyToken, async(req, res) => {
        const model = await require('../../model/Apply').find()
        res.send(model)
    })
    app.put('/api/apply/score/edit/:id', verifyToken, async(req, res) => {
        console.log('收到----------------');
        console.log(req.params.id);
        console.log(req.body);
        const model = await require('../../model/Apply').findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })
    app.post('/api/deleteApply/:id', verifyToken, async(req, res) => {
        const model = await require('../../model/Apply').findByIdAndDelete(req.params.id, req.body)
        res.send(model)
    })


}